<?php
class financeModel extends RPHP_Model
{

    protected $_auth = null;

    //检查权限
    public function checkPriv($pv, $return = true, $menu = true)
    {
        $this->_auth = $this->auth->CheckPriv($pv, $return, $menu);
        return $this->_auth;
    }

    //发放销售奖励
    public function sendOrderAwardMoney($da)
    {

        $my_order_money             = $da['my_order_money'];
        $level_total_money          = $da['level_total_money'];
        $subtract_total_order_money = $da['subtract_total_order_money'];
        $team_total_order_money     = $da['team_total_order_money'];
        $commission_rate            = $da['commission_rate'] ?: 0;
        $award_order_money          = number_format($da['award_money'], 2, ".", "");
        $uids                       = $da['uid'] ?: 0;
        $type                       = $da['type'] ?: 0;
        $caid                       = intval($da['caid']);
        $send_time                  = strtotime($da['start_time']);
        $cate                       = $this->table('goods_category')->findByPk($caid, "caid"); //分类信息
        if ($uids && $commission_rate && $cate['award_json'] && $send_time > 0 && $type > 0) {

            $this->db->begin();
            $commit = true;
            $time   = time();
            //配置信息（发送总金额）
            /* $config =  $this->getSetting();
            $award_order_money = $config['award_order_money'];*/
            $config = json_decode($cate['award_json'], true);
            if (!$award_order_money) {

                return array("code" => 901, "msg" => "请输入发放奖励金额");
            }

            $num = 0;
            //print_r($da);die;
            foreach ($uids as $v) {

                $award_log = $this->table("sell_award_log")->findBySql("`caid`=" . $caid . " AND `send_time`=" . $send_time . "  AND `uid`=" . $v);
                if (!$award_log && $commission_rate[$v] > 0 && $commit) {

                    $commit = false;

                    $num += 1;
                    //插入发放记录
                    $se['create_time'] = $time;
                    if ($my_order_money[$v]) {

                        $se['my_order_money'] = $my_order_money[$v];
                    }

                    if ($level_total_money[$v]) {

                        $se['level_total_money'] = $level_total_money[$v];
                    }

                    if ($subtract_total_order_money[$v]) {

                        $se['subtract_total_order_money'] = $subtract_total_order_money[$v];
                    }

                    if ($team_total_order_money[$v]) {

                        $se['team_total_order_money'] = $team_total_order_money[$v];
                    }

                    $se['capping_money']   = $config['capping_money'];
                    $se['send_time']       = $send_time;
                    $se['total_money']     = $award_order_money;
                    $se['commission_rate'] = $commission_rate[$v];
                    $se['uid']             = $v;
                    $se['caid']            = $caid;
                    $se['type']            = $type;
                    $se['send_money']      = number_format($commission_rate[$v] * $award_order_money, 2, ".", "");
                    if ($se['send_money'] > $se['capping_money']) {

                        $se['send_money'] = $se['capping_money'];

                    }

                    // print_r($se);die;

                    $log_id = $this->table("sell_award_log")->insert($se);

                    if ($log_id) {
                        $balance = $this->table("finance_balance")->findBySql("`uid`=" . $v);
                        if ($type == 1) {

                            $set         = "`money`=`money`+" . $se['send_money'] . ",`revenue`= `revenue`+" . $se['send_money'];
                            $bmoney      = $balance['money'] + $se['send_money'];
                            $brevenue    = $balance['revenue'] + $se['send_money'];
                            $event       = 26;
                            $detail_note = "获得销售硒豆奖励" . $se['send_money'];
                        } else {
                            $set         = "`gold_money`=`gold_money`+" . $se['send_money'];
                            $bmoney      = ($balance['gold_money'] + $se['send_money']);
                            $brevenue    = $balance['revenue'];
                            $event       = 28;
                            $detail_note = "获得销售金花奖励" . $se['send_money'];

                        }

                        // 更新资金表
                        $sql = "UPDATE {$this->_prefix['primary']}finance_balance SET " . $set . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . ",`random_num`=" . rand(100000, 999999) . " WHERE `uid`=" . $balance['uid'];
                        $rcs = $this->sql($sql);
                        if ($rcs > 0) {

                            $sql       = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`freeze`,`revenue`,`create_time`,`note`,`dataid`,`table_name`) VALUES (" . $balance['uid'] . "," . $event . "," . $se['send_money'] . "," . $bmoney . "," . $balance['freeze'] . "," . $brevenue . "," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "'," . $log_id . ",'sell_award_log')";
                            $detail_id = $this->sql($sql);
                            if ($detail_id > 0) {

                                $commit = true;

                            } else {
                                $code = 1004;
                            }

                        } else {
                            $code = 1003;
                        }

                    } else {
                        $code = 1002;
                    }

                } else {
                    $code = 1001;
                }
            }

            if ($commit) {

                $this->db->commit();
                if ($num) {

                    return array("code" => 200, "msg" => "发放成功");
                } else {

                    return array("code" => 902, "msg" => "已发放");
                }

            } else {
                return array("code" => $code, "msg" => "发放失败，请重新发放");
                $this->db->rollback();
            }

        }

        return array("code" => 900, "msg" => "发放失败，请重新发放");
    }

    //获取一级分类
    public function getCate()
    {
        $data = $this->table("goods_category")->findAllBySql("`stat`=1 AND `fucaid`=0", "`caid`,`name`,`award_json`");
        return $data;
    }

    //销售奖励统计
    public function getOrderAwardDetail($para)
    {
        if ($para['caid'] > 0 && $para['start_time'] != "" && $para['end_time'] != "") {
            $cate = $this->table('goods_category')->findByPk($para['caid'], "caid"); //分类信息
            if ($cate) {

                $date_time['start_time'] = strtotime($para['start_time']);
                $date_time['end_time']   = strtotime($para['end_time']);

                if ($_GET['teampercent'] != "") {
                    $teampercent = number_format($_GET['teampercent'], 2, ".", "");
                } else {
                    $teampercent = 0;
                }

                //所有下级分类集合
                $caids = $this->getCategoryIds($cate['caid']);

                //所属分类商品id集合
                $goods = $this->table("goods_data")->findAllBySql("`caid` IN (" . $caids . ")", "`goods_id`,`goods_name`");
                if ($goods) {

                    $goods_ids = ""; //商品id集合
                    foreach ($goods as $g) {
                        $goods_ids .= empty($goods_ids) ? $g['goods_id'] : "," . $g['goods_id'];

                    }
                    //echo $goods_ids;die;
                    if ($goods_ids) {

                        //统计会员信息
                        $members = $this->getAllMemberList();
                        if ($members['daili']) {

                            // 统计订单
                            $user_money = $this->getAllOrder($goods_ids, $date_time);

                            if ($user_money) {
                                // 循环代理
                                foreach ($members['daili'] as $dl) {

                                    $uids[] = $dl['uid'];

                                    $xhdl[$dl['uid']]['uid']    = $dl['uid'];
                                    $xhdl[$dl['uid']]['zigou']  = $user_money[$dl['uid']] ?: 0;
                                    $xhdl[$dl['uid']]['xiao']   = 0;
                                    $xhdl[$dl['uid']]['zhitui'] = 0;
                                    $xhdl[$dl['uid']]['zong']   = $xhdl[$dl['uid']]['zigou'];

                                    // 计算团队与直推业绩
                                    if ($members['child'][$dl['uid']]) {

                                        foreach ($members['child'][$dl['uid']] as $r) {

                                            $xhdl[$dl['uid']]['zhitui'] += $user_money[$r['uid']] > 0 ? $user_money[$r['uid']] : 0;
                                            unset($child);
                                            $child = $this->findAllChild($members['child'], $r['uid']);
                                            if ($child) {
                                                foreach ($child as $cuid) {
                                                    $xhdl[$dl['uid']]['team'][$r['uid']] += $user_money[$cuid] > 0 ? $user_money[$cuid] : 0;
                                                }
                                            }
                                        }

                                        $xhdl[$dl['uid']]['zong'] += $xhdl[$dl['uid']]['zhitui'];

                                        // 循环团队计算团队业绩与小市场业绩
                                        if ($xhdl[$dl['uid']]['team']) {
                                            //
                                            $big = 0;
                                            foreach ($xhdl[$dl['uid']]['team'] as $m) {
                                                if ($m > $big) {
                                                    $big = $m;
                                                }

                                                $xhdl[$dl['uid']]['zong'] += $m;

                                            }

                                            $xhdl[$dl['uid']]['xiao'] = $xhdl[$dl['uid']]['zong'] - $big;
                                        }
                                    }

                                }

                                $xiaonum = 0;

                                // 计算小市场总和

                                $award_config = json_decode($cate['award_json'], true);

                                foreach ($xhdl as $dluid => $d) {
                                    $xhdl[$dluid]['fenzi'] = $d['xiao'];
                                    if ($d['zigou'] >= $award_config['seft_money'] && $d['zhitui'] >= $award_config['re_money'] && $d['xiao'] >= $award_config['order_money'] && $d['zong'] >= $award_config['team_order_money']) {

                                        $xhdl[$dluid]['status'] = 1;

                                        $xiaoman += $d['xiao'];

                                        if ($teampercent > 0) {
                                            $xhdl[$dluid]['fenzi'] += floor($d['zong'] * $teampercent);

                                            $xiaoman += floor($d['zong'] * $teampercent);
                                        }

                                    }

                                    $xiaozong += $d['xiao'];
                                    $fenmu += $xhdl[$dluid]['fenzi'];
                                }

                                if ($xiaozong > 0) {
                                    foreach ($xhdl as $dluid => $d) {
                                        if ($d['status'] == 1) {
                                            $xiaonum += 1;
                                            $xhdl[$dluid]['commission_rate'] = floor($d['fenzi'] / $fenmu * 10000) / 10000;
                                        }
                                    }

                                    $xiaoman = floor($xiaoman / $xiaozong * 10000) / 10000;
                                }
                            }

                        }

                    }

                }

            }
        }

        if ($uids) {
            $sql = "SELECT `uid`,`name`,`realname`,`mobile`,`recode` FROM {$this->_prefix['primary']}member_account WHERE `uid` IN (" . implode(",", $uids) . ")";
            $tmp = $this->sql($sql);
            if ($tmp) {
                foreach ($tmp as $r) {
                    $user[$r['uid']] = $r;
                }
            }

        }

        $data = array(
            'daili'    => $xhdl,
            'xiaozong' => $xiaozong,
            'xiaoman'  => $xiaoman,
            'xiaonum'  => $xiaonum,
            'fenmu'    => $fenmu,
            'user'     => $user,
        );

        // print_r($data);

        return $data;

    }

    //所属商品订单信息
    public function getAllOrder($goods_ids = "", $date_time)
    {
        $start_time = $date_time['start_time']; //开始时间
        $end_time   = $date_time['end_time']; //结束时间

        $sql = "SELECT o.`uid`,g.`goods_price` * g.`goods_number` AS `money`  FROM {$this->_prefix['primary']}order_info AS o LEFT JOIN {$this->_prefix['primary']}order_goods AS g ON o.`order_id`= g.`order_id`  WHERE  o.`order_status` IN(1,7) AND o.`pay_status`=2 AND g.`goods_id` IN (" . $goods_ids . ")  AND o.`add_time`>=" . $start_time . " AND o.`add_time` <" . $end_time;

        $rs = $this->sql($sql);
        if ($rs) {
            foreach ($rs as $r) {
                $data[$r['uid']] += $r['money'];
            }
        }

        return $data;
    }

    // 获取所有会员
    public function getAllMemberList()
    {

        $tmp = $this->table('member_account')->findAllBySql("`stat`=1", "`uid`,`pid`,`member_level`");
        if ($tmp) {

            foreach ($tmp as $r) {
                if ($r['pid'] > 0) {
                    $child[$r['pid']][] = $r;
                }

                if ($r['member_level'] == 3) {
                    $members[$r['uid']] = $r;
                }
            }

        }

        return array(
            'daili' => $members,
            'child' => $child,
        );

    }

    public function findAllChild($child, $uid = 0, $data = false)
    {
        if ($child[$uid]) {
            foreach ($child[$uid] as $r) {
                $data[] = $r['uid'];
                if ($child[$r['uid']]) {
                    $data = $this->findAllChild($child, $r['uid'], $data);
                }
            }
        }

        return $data;
    }

    //获取所有下级分类id
    public function getCategoryIds($cat_id = 0, $data = '')
    {

        $rows = $this->table('goods_category')->findAllBySql("stat=1 and fucaid =" . $cat_id, "`caid`,`name`");
        if (empty($data)) {
            $data = $cat_id;

        }

        if ($rows) {

            foreach ($rows as $r) {
                if ($r['caid']) {
                    $data .= empty($data) ? $r['caid'] : "," . $r['caid'];
                    $data = $this->getCategoryIds($r['caid'], $data);
                }

            }
        }
        return $data;

    }

    //获取待入账记录
    public function getDRZ($para, $page, $pagesize = 20)
    {
        $where = " 1";
        if ($para) {

            if ($para['type']) {
                $where .= " AND fd.`type`=" . $para['type'];
            }
            if ($para['uid']) {
                $where .= " AND fd.`uid`=" . $para['uid'];
            }

            if ($para['start_time']) {
                $where .= " AND fd.`create_time` >=" . $para['start_time'];

                $para['start_time'] = date("Y-m-d", $para['start_time']);
            }

            if ($para['end_time']) {
                $where .= " AND fd.`create_time` <" . $para['end_time'];

                $para['end_time'] = date("Y-m-d", $para['end_time']);
            }

            if ($para['keyword'] != '') {
                if (is_numeric($para['keyword'])) {
                    $where .= " AND (ma.`mobile`= '" . $para['keyword'] . "' OR ma.`recode`='" . $para['keyword'] . "')";
                } else {
                    $where .= " AND  (ma.`realname` LIKE '%" . $para['keyword'] . "%' OR ma.`name` LIKE '%" . $para['keyword'] . "%')";
                }
            }
        }

        $sql = "SELECT COUNT(fd.`id`) AS `cnt` FROM {$this->_prefix['primary']}finance_drz AS fd LEFT JOIN {$this->_prefix['primary']}member_account AS ma ON ma.`uid`= fd.`uid`  WHERE " . $where;

        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "fd.`id` DESC";

            $sql = "SELECT fd.*,ma.`mobile`,ma.`realname`,ma.`name`,ma.`recode` FROM {$this->_prefix['primary']}finance_drz AS fd LEFT JOIN {$this->_prefix['primary']}member_account AS ma ON ma.`uid`= fd.`uid`  WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
            $rs  = $this->sql($sql);
            if ($rs) {
                foreach ($rs as $k => $r) {
                    if ($r['uid']) {
                        //获取用户昵称
                        $user_info = $this->getUsers($r['uid']);

                        $rs[$k]['user_name'] = $user_info['realname'];

                        if ($user_info['headimgurl'] > 0) {
                            $doc                  = $user_info['headimgurl'];
                            $r['headimgurl']      = $this->getDocs($doc);
                            $rs[$k]['headimgurl'] = $r['headimgurl'][$user_info['headimgurl']];
                        } else {
                            $rs[$k]['wechat_headimgurl'] = $user_info['wechat_headimgurl'];
                        }
                    }

                }

            }
        }

        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $rs,
            'para'    => $para,
        );
    }

    //获取会员收支明细
    public function getFinanceDetail($para, $page, $pagesize = 20)
    {
        $where = " 1";
        if ($para) {

            if ($para['event']) {
                $where .= " AND fd.`event`=" . $para['event'];
            }
            if ($para['uid']) {
                $where .= " AND fd.`uid`=" . $para['uid'];
            }

            if ($para['start_time']) {
                $where .= " AND fd.`create_time` >=" . $para['start_time'];

                $para['start_time'] = date("Y-m-d", $para['start_time']);
            }

            if ($para['end_time']) {
                $where .= " AND fd.`create_time` <" . $para['end_time'];

                $para['end_time'] = date("Y-m-d", $para['end_time']);
            }

            if ($para['keyword'] != '') {
                if (is_numeric($para['keyword'])) {
                    $where .= " AND (ma.`mobile`= '" . $para['keyword'] . "' OR ma.`recode`='" . $para['keyword'] . "')";
                } else {
                    $where .= " AND  (ma.`realname` LIKE '%" . $para['keyword'] . "%' OR ma.`name` LIKE '%" . $para['keyword'] . "%')";
                }
            }
        }

        $sql = "SELECT COUNT(*) AS `cnt` FROM {$this->_prefix['primary']}finance_detail AS fd LEFT JOIN {$this->_prefix['primary']}member_account AS ma ON ma.`uid`= fd.`uid`  WHERE " . $where;

        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "fd.`create_time` DESC,fd.`id` DESC";

            $sql = "SELECT fd.*,ma.`mobile`,ma.`realname`,ma.`name`,ma.`recode` FROM {$this->_prefix['primary']}finance_detail AS fd LEFT JOIN {$this->_prefix['primary']}member_account AS ma ON ma.`uid`= fd.`uid`  WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
            $rs  = $this->sql($sql);
            if ($rs) {
                foreach ($rs as $k => $r) {
                    if ($r['uid']) {
                        //获取用户昵称
                        $user_info = $this->getUsers($r['uid']);

                        $rs[$k]['user_name'] = $user_info['realname'];

                        if ($user_info['headimgurl'] > 0) {
                            $doc                  = $user_info['headimgurl'];
                            $r['headimgurl']      = $this->getDocs($doc);
                            $rs[$k]['headimgurl'] = $r['headimgurl'][$user_info['headimgurl']];
                        } else {
                            $rs[$k]['wechat_headimgurl'] = $user_info['wechat_headimgurl'];
                        }
                    }

                }

            }
        }

        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $rs,
            'para'    => $para,
        );
    }

    // 获取系统所有注册会员
    public function getAllMember($para)
    {
        $where = " `stat`=1 ";
        if ($para['info']) {
            if (is_numeric($para['info'])) {

                $where .= " AND `recode`='" . $para['info'] . "'";
            } else {
                $where .= " AND (`name` LIKE '%" . $para['info'] . "%')";

            }

            $sql = "SELECT `uid`,`name` FROM {$this->_prefix['primary']}member_account WHERE " . $where;
            return $this->sql($sql);
        }

    }

    public function getwithdrawStatistics($para)
    {
        $where = " 1=1 ";
        if ($para) {

            if (isset($para['status'])) {
                $where .= " AND `stat`=" . $para['status'];
            }

            if ($para['withdraw_type'] != '') {
                $where .= " AND `withdraw_type`=" . $para['withdraw_type'];
            }

            if ($para['money'] != '') {
                $where .= " AND `money` >='" . $para['money'] . "'";
            }
            if ($para['keyword'] != '') {
                if (is_numeric($para['keyword'])) {
                    $where .= " AND (`id`=" . intval($para['keyword']) . " OR `mobile`=" . $para['keyword'] . ")";
                } else {
                    $where .= " AND `realname` LIKE '%" . $para['keyword'] . "%'";
                }

            }

        }

        $sql = "SELECT `id`,`money`,`charge_fee` FROM {$this->_prefix['primary']}finance_withdraw WHERE " . $where;

        $rs          = $this->sql($sql);
        $total_money = 0;
        if ($rs) {
            foreach ($rs as $val) {

                $total_money += $val['money'];
            }
        }
        return number_format($total_money, 2, ".", "");
    }

    // 获取等待处理的提现信息
    public function getUntreatedData()
    {
        $sql  = "SELECT `id`,`money`,`realname`,`mobile`,`bank_sn`,`bank_account`,`note`,`create_time` FROM {$this->_prefix['primary']}finance_withdraw WHERE  `stat`=0 ORDER BY `id` ASC";
        $data = $this->sql($sql);

        return $data;
    }

    public function getWithdrowData($para)
    {

        $where = " 1=1 ";
        if ($para) {

            if (isset($para['status'])) {
                $where .= " AND `stat`=" . $para['status'];
            }

            if ($para['withdraw_type'] != '') {
                $where .= " AND `withdraw_type`=" . $para['withdraw_type'];
            }

            if ($para['money'] != '') {
                $where .= " AND `money` >='" . $para['money'] . "'";
            }
            if ($para['keyword'] != '') {
                if (is_numeric($para['keyword'])) {
                    $where .= " AND (`id`=" . intval($para['keyword']) . " OR `mobile`=" . $para['keyword'] . ")";
                } else {
                    $where .= " AND `realname` LIKE '%" . $para['keyword'] . "%'";
                }

            }

        }

        $sql = "SELECT * FROM {$this->_prefix['primary']}finance_withdraw WHERE " . $where . " ORDER BY `id` DESC";

        $rs = $this->sql($sql);

        if ($rs) {
            foreach ($rs as $k => $v) {
                if ($v['uid']) {
                    //获取用户昵称
                    $user_info           = $this->getUsers($v['uid']);
                    $rs[$k]['user_name'] = $user_info['realname'];
                }

            }

        }

        return $rs;

    }

    //保存提现信息
    public function saveWithdraw($da)
    {

        $code = 404;
        $id   = intval($da['id']);

        $data = $this->getSingleWithdraw($id);
        //print_r($data);die;
        if ($da) {

            //设为正在处理中
            if ($da['act'] == "process") {
                $sql = "UPDATE {$this->_prefix['primary']}finance_withdraw SET `stat`='1',`last_aid`='" . $this->_auth['aid'] . "',`last_edit`='" . $_SERVER['REQUEST_TIME'] . "' WHERE `id`=" . $data['id'];
                // print_r($sql);die;
                $rc = $this->sql($sql);
                if ($rc > 0) {
                    $code = 200;
                }

            }
            //设为成功
            elseif ($da['act'] == "done") {

                //开始事务
                $this->db->begin();
                $rollback    = true;
                $money       = $data['charge_fee'] + $data['money'];
                $trande_no   = addslashes(htmlspecialchars(trim($da['trade_no'])));
                $trande_fee  = number_format($da['trade_fee'], 2, ".", "");
                $trande_time = strtotime($da['trade_time']);
                //print_r($da);die;
                $trande_note = addslashes(htmlspecialchars(trim($da['trade_note'])));

                $sql = "UPDATE {$this->_prefix['primary']}finance_withdraw SET `trade_no`='" . $trande_no . "',`trade_fee`='" . $trande_fee . "',`trade_time`='" . $trande_time . "',`trade_note`='" . $trande_note . "',`stat`='2',`last_aid`='" . $this->_auth['aid'] . "',`last_edit`='" . $_SERVER['REQUEST_TIME'] . "' WHERE `id`=" . $data['id'];
                $rc  = $this->sql($sql);
                if ($rc > 0) {
                    $balance = $this->db->getrow("SELECT * FROM {$this->_prefix['primary']}finance_balance WHERE `uid`=" . $data['uid']);
                    if ($da['coin_type'] == 1) {
                        //扣除肽币冻结资金
                        $sql = "UPDATE {$this->_prefix['primary']}finance_balance SET `freeze`=`freeze`-" . $money . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . " WHERE `uid`=" . $data['uid'];
                        $rd  = $this->sql($sql);
                        if ($rd > 0) {
                            //插入肽币资金明细
                            $detail_note = '提现成功，扣除冻结的资金' . $money . '元';
                            $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`freeze`,`dataid`,`table_name`,`create_time`,`note`) VALUES (" . $data['uid'] . ",6," . $money . "," . $balance['money'] . "," . ($balance['freeze'] - $money) . "," . $data['id'] . ",'finance_withdraw'," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "')";
                            $detail_id   = $this->sql($sql);
                            if ($detail_id > 0) {

                                $code = 200;
                                $this->db->commit();
                                $rollback = false;
                            }

                        }

                    } else {

                        //扣除九云币冻结资金
                        $sql = "UPDATE {$this->_prefix['primary']}finance_balance SET `freeze_coins_money`=`freeze_coins_money`-" . $money . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . " WHERE `uid`=" . $data['uid'];
                        $rd  = $this->sql($sql);
                        if ($rd > 0) {
                            //插入九云币资金明细
                            $detail_note = '提现成功，扣除冻结的资金' . $money . '元';
                            $sql         = "INSERT INTO {$this->_prefix['primary']}finance_coins (`uid`,`event`,`cmoney`,`money`,`freeze`,`dataid`,`table_name`,`create_time`,`note`) VALUES (" . $data['uid'] . ",6," . $money . "," . $balance['money'] . "," . ($balance['freeze_coins_money'] - $money) . "," . $data['id'] . ",'finance_withdraw'," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "')";
                            $detail_id   = $this->sql($sql);
                            if ($detail_id > 0) {

                                $code = 200;
                                $this->db->commit();
                                $rollback = false;
                            }

                        }
                    }

                }

                if ($rollback) {
                    $this->db->rollback();
                }

            }
            //设为失败
            elseif ($da['act'] == "cancel") {

                //开始事务
                $this->db->begin();
                $rollback = true;

                $money = $data['charge_fee'] + $data['money'];

                $sql = "UPDATE {$this->_prefix['primary']}finance_withdraw SET `stat`='3',`last_aid`='" . $this->_auth['aid'] . "',`last_edit`='" . $_SERVER['REQUEST_TIME'] . "' WHERE `id`=" . $data['id'];
                $rc  = $this->sql($sql);
                if ($rc > 0) {
                    $balance = $this->db->getrow("SELECT `money`,`freeze`,`coins_money`,`freeze_coins_money` FROM {$this->_prefix['primary']}finance_balance WHERE `uid`=" . $data['uid']);

                    if ($da['coin_type'] == 1) {
                        //恢复肽币冻结资金
                        $sql = "UPDATE {$this->_prefix['primary']}finance_balance SET `money`=`money`+" . $money . ",`revenue`=`revenue`+" . $money . ",`freeze`=`freeze`-" . $money . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . " WHERE `uid`=" . $data['uid'];
                        $rd  = $this->sql($sql);
                        if ($rd > 0) {
                            //插入资金明细
                            $detail_note = '提现失败，解除冻结的资金' . $money . '元';
                            $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`freeze`,`dataid`,`table_name`,`create_time`,`note`) VALUES (" . $data['uid'] . ",5," . $money . "," . ($balance['money'] + $money) . "," . ($balance['freeze'] - $money) . "," . $data['id'] . ",'finance_withdraw'," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "')";
                            $detail_id   = $this->sql($sql);
                            if ($detail_id > 0) {

                                $code = 200;
                                $this->db->commit();
                                $rollback = false;
                            }

                        }
                    } else {
                        //恢复九云币冻结资金
                        $sql = "UPDATE {$this->_prefix['primary']}finance_balance SET `coins_money`=`coins_money`+" . $money . ",`freeze_coins_money`=`freeze_coins_money`-" . $money . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . " WHERE `uid`=" . $data['uid'];
                        $rd  = $this->sql($sql);
                        if ($rd > 0) {
                            //插入资金明细
                            $detail_note = '提现失败，解除冻结的资金' . $money . '元';
                            $sql         = "INSERT INTO {$this->_prefix['primary']}finance_coins (`uid`,`event`,`cmoney`,`money`,`freeze`,`dataid`,`table_name`,`create_time`,`note`) VALUES (" . $data['uid'] . ",5," . $money . "," . ($balance['coins_money'] + $money) . "," . ($balance['freeze_coins_money'] - $money) . "," . $data['id'] . ",'finance_withdraw'," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "')";
                            $detail_id   = $this->sql($sql);
                            if ($detail_id > 0) {

                                $code = 200;
                                $this->db->commit();
                                $rollback = false;
                            }

                        }

                    }

                }

                if ($rollback) {
                    $this->db->rollback();
                }

            }

        }

        return $code;

    }

    //获取单条提现信息
    public function getSingleWithdraw($id, $getuserinfo = true)
    {
        $sql  = "SELECT * FROM {$this->_prefix['primary']}finance_withdraw WHERE `id`=" . intval($id);
        $data = $this->db->getrow($sql);
        if ($data && $getuserinfo) {
            $data['userinfo'] = $this->getUsers($data['uid']);
            $data['openid']   = $this->getMemberWeiXin($data['uid']);
        }
        return $data;
    }

    //获取打印注册订单详情
    public function getWithdrawPrintDetail($order_id)
    {

        $sql  = "SELECT * FROM {$this->_prefix['primary']}member_payinfo WHERE `order_id`=" . intval($order_id);
        $data = $this->db->getrow($sql);
        // 区域信息
        if ($data['tao_province_id'] > 0) {
            $region_id[] = $data['tao_province_id'];
        }

        if ($data['tao_city_id'] > 0) {
            $region_id[] = $data['tao_city_id'];
        }

        if ($data['tao_county_id'] > 0) {
            $region_id[] = $data['tao_county_id'];
        }

        if ($region_id) {
            $sql         = "SELECT `region_id`,`region_name` FROM {$this->_prefix['primary']}region WHERE `region_id` IN (" . implode(",", $region_id) . ")";
            $region_data = $this->sql($sql);
            if ($region_data) {
                foreach ($region_data as $r) {
                    $region[$r['region_id']] = $r['region_name'];
                }

                $data['region'] = $region;
            }
        }

        return $data;

    }

    //提现列表
    public function getWithdrawList($para, $page = 1, $pagesize = 20)
    {

        $where = " 1=1 ";
        if ($para) {

            if (isset($para['status'])) {
                $where .= " AND `stat`=" . $para['status'];
            }

            if ($para['withdraw_type'] != '') {
                $where .= " AND `withdraw_type`=" . $para['withdraw_type'];
            }

            if ($para['coin_type'] != '') {
                $where .= " AND `coin_type`=" . $para['coin_type'];
            }

            if ($para['money'] != '') {
                $where .= " AND `money` >='" . $para['money'] . "'";
            }
            if ($para['keyword'] != '') {
                if (is_numeric($para['keyword'])) {
                    $where .= " AND (`id`=" . intval($para['keyword']) . " OR `mobile`=" . $para['keyword'] . ")";
                } else {
                    $where .= " AND `realname` LIKE '%" . $para['keyword'] . "%'";
                }

            }

        }

        $sql = "SELECT COUNT(`id`) AS `cnt` FROM {$this->_prefix['primary']}finance_withdraw WHERE " . $where;

        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`id` DESC";

            $sql = "SELECT * FROM {$this->_prefix['primary']}finance_withdraw WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;

            $rs = $this->sql($sql);

            if ($rs) {
                foreach ($rs as &$r) {
                    if ($r['uid']) {
                        //获取用户昵称
                        $user_info      = $this->getUsers($r['uid']);
                        $r['user_name'] = $user_info['realname'];

                        if ($user_info['headimgurl'] > 0) {
                            $doc             = $user_info['headimgurl'];
                            $r['headimgurl'] = $this->getDocs($doc);
                            $r['headimgurl'] = $r['headimgurl'][$user_info['headimgurl']];
                        } else {
                            $r['wechat_headimgurl'] = $user_info['wechat_headimgurl'];
                        }
                    }
                }

            }

        }

        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $rs,
            'para'    => $para,
        );
    }

    //获取用户昵称和头像
    public function getUserInfo($uids)
    {

        $sql = "SELECT * FROM {$this->_prefix['primary']}member_wechat WHERE `uid` IN (" . implode(",", array_unique($uids)) . ")";

        $data = $this->sql($sql);
        if ($data) {
            foreach ($data as $r) {
                $user[$r['uid']] = $r;
            }
            return $user;
        } else {
            return false;
        }

    }

    public function getUsers($uid)
    {

        $sql = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE `uid`=" . $uid;

        $data = $this->db->getrow($sql);
        if ($data) {

            return $data;
        } else {
            return false;
        }

    }

    public function getUserMoney($uid)
    {

        $sql = "SELECT * FROM {$this->_prefix['primary']}finance_balance WHERE `uid`=" . $uid;

        return $this->db->getrow($sql);

    }

    // 统计明细信息
    public function totalDetail($da)
    {

        $sql         = "SELECT SUM(`cmoney`) AS `total` FROM {$this->_prefix['primary']}finance_detail WHERE 1";
        $da['event'] = intval($da['event']);

        if ($da['event'] > 0) {
            $sql .= " AND `event`=" . $da['event'];
        }

        if ($da['start_time'] != "") {
            $start_time = strtotime($da['start_time'] . " 0:0:0");
            $sql .= " AND `create_time`>=" . $start_time;
        }
        if ($da['end_time'] != "") {
            $end_time = strtotime($da['end_time'] . " 23:59:59");
            $sql .= " AND `create_time`<=" . $end_time;
        }
        // echo $sql;
        $money = $this->db->getone($sql);
        return $money;
    }

    public function getDocs($docid)
    {
        if (is_array($docid)) {
            $where = " WHERE `docid` IN (" . implode(",", array_unique($docid)) . ")";
        } else {
            $where = " WHERE `docid`=" . intval($docid);
        }

        $sql = "SELECT `docid`,`filename`,`create_time` FROM {$this->_prefix['primary']}documents " . $where;
        $rs  = $this->sql($sql);
        if ($rs) {
            foreach ($rs as $r) {
                $doc[$r['docid']] = $this->c['doc_host'] . date("Ymd", $r['create_time']) . "/" . date("H", $r['create_time']) . "/" . date("i", $r['create_time']) . "/" . $r['filename'];

            }
            return $doc;
        } else {
            return false;
        }

    }

    // 获取设置
    public function getSetting()
    {
        $sql     = "SELECT `setting` FROM {$this->_prefix['primary']}setting ORDER BY `setting_id` DESC LIMIT 1";
        $setting = $this->db->getone($sql);
        if ($setting != "") {
            return json_decode($setting, true);
        }

    }

    // 获取微信设置
    public function getWeiXinSetting()
    {
        $sql   = "SELECT `appid` FROM {$this->_prefix['primary']}weixin_setting";
        $appid = $this->db->getone($sql);

        if ($appid != "") {
            return $appid;
        }

    }

    // 获取用户微信信息
    public function getMemberWeiXin($uid)
    {
        $sql    = "SELECT  `openid` FROM {$this->_prefix['primary']}member_wechat WHERE `uid`=" . $uid;
        $openid = $this->db->getone($sql);

        if ($openid != "") {
            return $openid;
        }

    }

    public function getFinanceDetailData($start_time = 0, $end_time = 0, $event = 0, $keyword = '')
    {

        $where = '1';

        if ($start_time) {
            $where .= " AND fd.`create_time` >=" . $start_time;

        }

        if ($end_time) {
            $where .= " AND fd.`create_time` <" . $end_time;

        }

        if ($event) {
            $where .= " AND fd.`event`=" . $event;
        }

        if ($keyword != '') {
            if (is_numeric($keyword)) {
                $where .= " AND  (ma.`mobile`= '" . $keyword . "' OR ma.`recode`='" . $keyword . "')";
            } else {
                $where .= " AND  (ma.`realname` LIKE '%" . $keyword . "%' OR ma.`name` LIKE '%" . $keyword . "%')";
            }
        }

        $sql = "SELECT fd.*,ma.`mobile`,ma.`realname`,ma.`name`,ma.`recode` FROM {$this->_prefix['primary']}finance_detail AS fd LEFT JOIN {$this->_prefix['primary']}member_account AS ma ON ma.`uid`= fd.`uid`  WHERE " . $where . " ORDER BY  fd.`create_time` DESC";
        $rs  = $this->sql($sql);

        if ($rs) {
            foreach ($rs as $k => $r) {
                /*        if ($r['uid']) {
                //获取用户昵称
                $user_info = $this->getUsers($r['uid']);
                $rs[$k]['realname'] = $user_info['realname'];
                $rs[$k]['recode'] =  $user_info['recode'];
                $rs[$k]['mobile'] =  $user_info['mobile'];
                $rs[$k]['name'] =  $user_info['name'];
                } */

                switch ($r['event']) {
                    case 1:
                        $rs[$k]['eventS'] = "充值";
                        break;
                    case 2:
                        $rs[$k]['event'] = "消费";
                        break;
                    case 3:
                        $rs[$k]['event'] = "收入";
                        break;
                    case 4:
                        $rs[$k]['event'] = "冻结";
                        break;
                    case 5:
                        $rs[$k]['event'] = "解冻";
                        break;
                    case 6:
                        $rs[$k]['event'] = "提现";
                        break;
                    case 7:
                        $rs[$k]['event'] = "退款";
                        break;
                    case 8:
                        $rs[$k]['event'] = "分润";
                        break;
                    case 9:
                        $rs[$k]['event'] = "管理费";
                        break;

                }

                if ($r['member_level'] == 0 && $user_info['mobile'] == "") {

                    $rs[$k]['member_level'] = "用户";
                } else {

                    if ($r['member_level'] == 0) {

                        $rs[$k]['member_level'] = "游客";
                    } else if ($r['member_level'] == 1) {

                        $rs[$k]['member_level'] = "会员";
                    } else if ($r['member_level'] == 2) {

                        $rs[$k]['member_level'] = "加盟店";
                    } else if ($r['member_level'] == 3) {

                        $rs[$k]['member_level'] = "加盟仓";
                    }
                }

            }

        }

        return array('data' => $rs);
    }

    // 获取区域信息
    public function getRegion()
    {
        $sql  = "SELECT `region_id`,`region_name` FROM {$this->_prefix['primary']}region ORDER BY `region_id` ASC";
        $data = $this->sql($sql);
        if ($data) {
            foreach ($data as $r) {
                $new[$r['region_id']] = $r['region_name'];
            }

            return $new;
        }
    }

}
